<style lang="scss" scoped>
  $size: 4vw;
  .search {
    &.search_show {
      position: fixed;
      z-index: 1111;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background: #ddd;
      & /deep/ .search_input {
        display: flex;
        input {
          padding-left: 6vw !important;
          padding-right: 6vw !important;
          margin-right: 2vw;
        }
      }
    }
    & > * {
      background: #fff;
    }
    & /deep/ [class^=icon_] {
      position: absolute;
      font-size: $size;
      top: 3.4vw;
    }
  }
</style>

<template lang="pug">
  .search(:class="{search_show: show}")
    search-input(:show.sync="show" :place="place" v-model="val" :storageShow.sync="storageShow" @search="search" :loading.sync="loading")
    search-cookie(:show.sync="show" :storageData="storageData" :val.sync="val" v-if="show" :storageShow.sync="storageShow" @delCookie="delCookie" :loading.sync="loading")
</template>

<script>
  import {mapState, mapGetters, mapMutations} from 'vuex'
  import searchInput from './input'
  import searchCookie from './cookie/index'
  export default {
    name: "search",
    props: {
      place: {
        type: String,
        default: '搜索',
      },
      sCookie: String,//操作的cookie
    },
    data() {
      return {
        show: false,//进入搜索布局
        storageShow: true,//是否显示cookie
        loading: false,
        val: '',
        storageData: [],
      }
    },
    computed: {
      ...mapState([]),
      ...mapGetters([]),

    },
    methods: {
      ...mapMutations([]),
      init (){
        let sCookie = localStorage.getItem(this.sCookie);
        if(sCookie === null){
          this.setLocalStorage();
        }else {
          if(sCookie !== ''){
            this.storageData = sCookie.split(',');
          }
        }
      },
      delCookie(val) {
        console.log(val);
        if( isNaN(val) ) {
          this.storageData = [];
        }else {
          this.storageData.splice(val, 1)
        }
        this.setLocalStorage();
      },
      setLocalStorage() {
        localStorage.setItem(this.sCookie, this.storageData)
      },
      search() {
        let storageData = this.storageData;
        if( storageData[0] === this.val) return;
        if( storageData.indexOf(this.val) !== -1 ) {
          storageData.splice(storageData.findIndex( val => val === this.val ), 1)
        }
        storageData.unshift(this.val);
        this.setLocalStorage();
        this.loading = true;
        this.$emit('search', this.val)
      }
    },
    created() {
      this.init();
    },
    mounted() {

    },
    components: {
      searchInput,
      searchCookie
    }
  }
</script>

